Node.js Interface Reference

Node.js readline Interface

ইন্টারফেস অবজেক্ট

ইন্টারফেস ক্লাস Node.js-এর রিডলাইন মডিউলের অংশ। এটি একটি পঠনযোগ্য স্ট্রিম (যেমন process.stdin) থেকে একবারে একটি লাইন থেকে ডেটা পড়ার একটি উপায় প্রদান করে। এটি সাধারণত কমান্ড-লাইন ইন্টারফেস (CLIs) এবং ইন্টারেক্টিভ কোয়েরি তৈরি করতে ব্যবহৃত হয়।

কমান্ড লাইন ইন্টারফেস

CLI অ্যাপ্লিকেশন এবং কমান্ড টুল তৈরি করতে সাহায্য করে

ইন্টারেক্টিভ প্রশ্ন

ব্যবহারকারীদের কাছ থেকে ইনপুট পেতে ইন্টারেক্টিভ উপায় প্রদান করে

স্ট্রিম ম্যানিপুলেশন

পঠনযোগ্য এবং লেখার যোগ্য স্ট্রিমগুলির সাথে সরাসরি কাজ করে

রিডলাইন মডিউল আমদানি করা হচ্ছে

// Import the readline module
const readline = require('readline');

// Create an Interface instance
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

ইন্টারফেস বৈশিষ্ট্য

বৈশিষ্ট্য ব্যাখ্যা
rl.line ইনপুট লাইন বর্তমানে প্রক্রিয়া করা হচ্ছে
rl.cursor বর্তমান লাইনে কার্সারের অবস্থান
rl.input পঠনযোগ্য স্ট্রীম ব্যবহার করা হয়েছে
rl.output লিখনযোগ্য স্ট্রীম ব্যবহার করা হবে
rl.terminal বুলিয়ান নির্দেশ করে যে স্ট্রিমটিকে TTY হিসাবে বিবেচনা করা উচিত এবং ANSI/VT100 এস্কেপ কোড লেখা উচিত কিনা।
rl.history যদি একটি ইতিহাস বাফার প্রদান করা হয়. একটি প্রতিশ্রুতি-ভিত্তিক API ব্যবহার করার সময় এটি উপলব্ধ নয়

ইন্টারফেস পদ্ধতি

পদ্ধতি ব্যাখ্যা
rl.question(query, callback) ব্যবহারকারীকে প্রশ্ন দেখায় এবং তাদের ইনপুটের জন্য অপেক্ষা করে। একবার সেগুলি প্রদান করা হলে, এটি প্রথম যুক্তি হিসাবে ব্যবহারকারীর ইনপুট সহ কলব্যাককে কল করে৷
rl.close() ইন্টারফেস ইনস্ট্যান্স বন্ধ করে, ইনপুট এবং আউটপুট স্ট্রীমের নিয়ন্ত্রণ ত্যাগ করে
rl.pause() রিডলাইন ইনপুট স্ট্রীমকে বিরতি দেয়, এটি পরে আবার শুরু করার অনুমতি দেয়
rl.resume() রিডলাইন ইনপুট স্ট্রীম পুনরায় শুরু করে
rl.write(data[, key]) আউটপুট স্ট্রীমে ডেটা লেখে। মূল যুক্তিটি এমন একটি বস্তু হতে পারে যাতে বিশেষ অক্ষর থাকে যেমন ctrl বা meta
rl.prompt([preserveCursor]) ব্যবহারকারীর ইনপুটের জন্য একটি প্রম্পট প্রদর্শন করে। preserveCursor সত্য হলে, কার্সারের অবস্থান পুনরায় সেট করা হয় না
rl.getPrompt() বর্তমান প্রম্পট স্ট্রিং প্রদান করে
rl.setPrompt(prompt) rl.prompt() prompt

ইন্টারফেস ঘটনা

ঘটনা ব্যাখ্যা
'close' ইন্টারফেস ইভেন্ট বন্ধ হলে নির্গত হয়
'line' ব্যবহারকারী যখন এন্টার কী টিপে এবং ইনপুটের একটি লাইন জমা দেয় তখন নির্গত হয়
'pause' ইনপুট স্ট্রীম পজ করা হলে নির্গত হয়
'resume' ইনপুট স্ট্রীম পুনরায় চালু হলে নির্গত হয়
'SIGCONT' যখন একটি Node.js প্রক্রিয়া যা পূর্বে Ctrl+Z (SIGTSTP) দিয়ে বিরাম দেওয়া হয়েছিল তা পুনরায় শুরু হলে নির্গত হয়
'SIGINT' Ctrl+C চাপলে নির্গত হয়, যা SIGINT নামে পরিচিত
'SIGTSTP' Ctrl+Z চাপলে নির্গত হয়, যা SIGTSTP নামে পরিচিত
'history' ইতিহাস পরিবর্তিত হলেই নির্গত হয়

বেসিক অ্যাপ্লিকেশন উদাহরণ

এই উদাহরণটি একটি সাধারণ কমান্ড লাইন প্রম্পট তৈরি করতে ইন্টারফেস অবজেক্টের মৌলিক ব্যবহার প্রদর্শন করে:

const readline = require('readline');

// Create interface for reading from stdin and writing to stdout
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

// Ask a question and get the user's input
rl.question('What is your name? ', (name) => {
  console.log(`Hello, ${name}!`);

  // Ask another question
  rl.question('How are you today? ', (response) => {
    console.log(`Glad to hear: ${response}`);
    
    // Close the interface
    rl.close();
  });
});

// Handle the close event
rl.on('close', () => {
  console.log('Interface closed. Goodbye!');
});

প্রতিশ্রুতি-ভিত্তিক API উদাহরণ

Node.js v17+ readline promise- API :

// For Node.js v17 and above:
const readline = require('readline/promises');
const { stdin: input, stdout: output } = require('process');

async function askQuestions() {
  const rl = readline.createInterface({ input, output });

  try {
    // Ask questions sequentially
    const name = await rl.question('What is your name? ');
    console.log(`Hello, ${name}!`);

    const age = await rl.question('How old are you? ');
    console.log(`You are ${age} years old.`);

    const location = await rl.question('Where do you live? ');
    console.log(`${location} is a nice place!`);

    // Summary
    console.log('\nSummary:');
    console.log(`Name: ${name}`);
    console.log(`Age: ${age}`);
    console.log(`Location: ${location}`);
  } finally {
    // Make sure to close the interface
    rl.close();
  }
}

// Run the async function
askQuestions()
  .then(() => console.log('Questions completed!'))
  .catch(err => console.error('Error:', err));

কমান্ড লাইন ইন্টারফেস উদাহরণ

ইতিহাস সমর্থন সহ একটি সাধারণ কমান্ড লাইন ইন্টারফেস তৈরি করা:

const readline = require('readline');
const fs = require('fs');
const path = require('path');

// History file path
const historyFile = path.join(__dirname, '.command_history');

// Load command history if it exists
let commandHistory = [];
try {
  if (fs.existsSync(historyFile)) {
    commandHistory = fs.readFileSync(historyFile, 'utf8')
      .split('\n')
      .filter(cmd => cmd.trim());
  }
} catch (err) {
  console.error('Error loading history:', err.message);
}

// Create the interface with custom configuration
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  prompt: 'cli> ',
  historySize: 100,
  history: commandHistory
});

// Available commands
const commands = {
  help: () => {
    console.log('\nAvailable commands:');
    console.log('  help     - Show this help message');
    console.log('  hello    - Say hello');
    console.log('  date     - Show current date and time');
    console.log('  clear    - Clear the console');
    console.log('  exit     - Exit the CLI');
    rl.prompt();
  },
  hello: () => {
    console.log('Hello, world!');
    rl.prompt();
  },
  date: () => {
    console.log(new Date().toLocaleString());
    rl.prompt();
  },
  clear: () => {
    process.stdout.write('\x1Bc');
    rl.prompt();
  },
  exit: () => {
    // Save command history to file
    try {
      fs.writeFileSync(historyFile, rl.history.join('\n'));
      console.log(`Command history saved to ${historyFile}`);
    } catch (err) {
      console.error('Error saving history:', err.message);
    }
    
    console.log('Goodbye!');
    rl.close();
  }
};

// Display welcome message
console.log('Simple CLI Example');
console.log('Type "help" for available commands');

// Display the prompt
rl.prompt();

// Handle input
rl.on('line', (line) => {
  const input = line.trim();
  
  if (input === '') {
    rl.prompt();
    return;
  }
  
  const command = input.toLowerCase();
  
  if (commands[command]) {
    commands[command]();
  } else {
    console.log(`Command not found: ${input}`);
    console.log('Type "help" for available commands');
    rl.prompt();
  }
}).on('close', () => {
  process.exit(0);
});

// Handle Ctrl+C (SIGINT)
rl.on('SIGINT', () => {
  rl.question('Are you sure you want to exit? (y/n) ', (answer) => {
    if (answer.toLowerCase() === 'y') {
      commands.exit();
    } else {
      console.log('Operation cancelled');
      rl.prompt();
    }
  });
});

ইন্টারেক্টিভ পাসওয়ার্ড এন্ট্রি

একটি পাসওয়ার্ড এন্ট্রি তৈরি করা যা প্রবেশ করা অক্ষরগুলিকে লুকিয়ে রাখে:

const readline = require('readline');

// Create the interface
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

// Function to prompt for masked input
function promptPassword(query) {
  return new Promise((resolve) => {
    // Create a hidden readline instance to control input/output
    const stdin = process.stdin;
    
    // Save the original configuration
    const originalStdinIsTTY = stdin.isTTY;
    if (originalStdinIsTTY) {
      stdin.setRawMode(true);
    }
    
    let password = '';
    
    // Write the query
    process.stdout.write(query);
    
    // Handle keypress events
    const onData = (key) => {
      // Ctrl+C
      if (key.toString() === '\u0003') {
        process.stdout.write('\n');
        process.exit();
      }
      
      // Enter key
      if (key.toString() === '\r' || key.toString() === '\n') {
        if (originalStdinIsTTY) {
          stdin.setRawMode(false);
        }
        stdin.removeListener('data', onData);
        process.stdout.write('\n');
        resolve(password);
        return;
      }
      
      // Backspace
      if (key.toString() === '\u0008' || key.toString() === '\u007f') {
        if (password.length > 0) {
          password = password.slice(0, -1);
          process.stdout.write('\b \b'); // Erase last character
        }
        return;
      }
      
      // Regular character
      password += key.toString();
      process.stdout.write('*'); // Show asterisk for each character
    };
    
    stdin.on('data', onData);
  });
}

// Example usage
async function login() {
  const username = await new Promise((resolve) => {
    rl.question('Username: ', (answer) => {
      resolve(answer);
    });
  });
  
  const password = await promptPassword('Password: ');
  
  console.log(`\nAttempting login for user: ${username}`);
  
  // Simulate authentication check
  if (username === 'admin' && password === 'password') {
    console.log('Login successful!');
  } else {
    console.log('Invalid username or password');
  }
  
  rl.close();
}

// Start the login process
login();

ইন্টারেক্টিভ মেনু উদাহরণ

বিকল্পগুলির সাথে একটি ইন্টারেক্টিভ মেনু তৈরি করা:

const readline = require('readline');

// Create the interface
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

// Menu options
const menuOptions = [
  { id: 1, name: 'View Profile' },
  { id: 2, name: 'Edit Settings' },
  { id: 3, name: 'Check Messages' },
  { id: 4, name: 'Log Out' },
  { id: 5, name: 'Exit' }
];

// Display the menu
function displayMenu() {
  console.log('\n===== MAIN MENU =====');
  menuOptions.forEach(option => {
    console.log(`${option.id}. ${option.name}`);
  });
  console.log('====================');
}

// Process the selected option
function processOption(option) {
  const selectedOption = menuOptions.find(item => item.id === parseInt(option));
  
  if (!selectedOption) {
    console.log('Invalid option. Please try again.');
    return promptUser();
  }
  
  console.log(`\nYou selected: ${selectedOption.name}`);
  
  // Handle each option
  switch (selectedOption.id) {
    case 1:
      console.log('Displaying user profile...');
      console.log('Name: John Doe');
      console.log('Email: john@example.com');
      console.log('Role: Administrator');
      break;
    case 2:
      console.log('Opening settings menu...');
      console.log('(Settings options would be displayed here)');
      break;
    case 3:
      console.log('Checking messages...');
      console.log('You have no new messages.');
      break;
    case 4:
      console.log('Logging out...');
      console.log('You have been logged out successfully.');
      return rl.close();
    case 5:
      console.log('Exiting the application...');
      return rl.close();
  }
  
  // Return to the menu after a short delay
  setTimeout(() => {
    promptUser();
  }, 1500);
}

// Prompt the user to select an option
function promptUser() {
  displayMenu();
  rl.question('Select an option: ', (answer) => {
    processOption(answer);
  });
}

// Start the menu
console.log('Welcome to the Interactive Menu Example');
promptUser();

// Handle close event
rl.on('close', () => {
  console.log('\nThank you for using the application!');
  process.exit(0);
});

সর্বোত্তম অনুশীলন

সর্বদা ইন্টারফেস বন্ধ করুন:রিসোর্স রিলিজ করা হয়ে গেলে rl.close() এ কল করুন
Ctrl+C হ্যান্ডেল:প্রোগ্রামের ফলাফলকে সুন্দরভাবে পরিচালনা করতে 'SIGINT' ইভেন্টটি শুনুন
একটি প্রতিশ্রুতি ভিত্তিক API ব্যবহার করুন: Node.js v17 , async promise- API
ইতিহাস সংরক্ষণ করুন:CLI অ্যাপ্লিকেশনগুলির জন্য, একটি ভাল ব্যবহারকারীর অভিজ্ঞতা প্রদান করতে কমান্ড ইতিহাস সংরক্ষণ এবং পুনরুদ্ধার করুন
ত্রুটিগুলি পরিচালনা করুন:ব্যবহারকারীর সাথে ইন্টারঅ্যাক্ট করার সময় সর্বদা সম্ভাব্য ত্রুটিগুলি পরিচালনা করুন
স্পষ্ট প্রম্পট প্রদান করুন:নিশ্চিত করুন যে আপনার প্রম্পট স্পষ্টভাবে নির্দেশ করে যে কি ধরনের ইনপুট প্রত্যাশিত
এন্ট্রি পরীক্ষা করুন:এটি প্রক্রিয়া করার আগে সর্বদা ব্যবহারকারীর ইনপুট যাচাই করুন

অনুশীলন করুন

Node.js readline Interface .

readline.startInterface()
✗ ভুল! "readline.startInterface()" Node.js-এ একটি বৈধ পদ্ধতি নয়
readline.newInterface()
✗ ভুল! "readline.newInterface()" Node.js-এ একটি বৈধ পদ্ধতি নয়
readline.createInterface()
✓ ঠিক আছে! "readline.createInterface()" হল সঠিক পদ্ধতি যা Node.js এ রিডলাইন ইন্টারফেস তৈরি করতে ব্যবহৃত হয়
readline.initInterface()
✗ ভুল! "readline.initInterface()" Node.js-এ একটি বৈধ পদ্ধতি নয়